<?php
declare(strict_types=1);

// +----------------------------------------------------------------------
// | SCApi
// +----------------------------------------------------------------------
// | 版权所有 2021~2022 贾二小 [ http://www.ipsoul.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://www.ipsoul.com
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// | 免费声明 ( http://doc.ipsoul.com/disclaimer )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/jiaerxiao/scapi
// | github 代码仓库：https://github.com/jiaerxiao/scapi
// +----------------------------------------------------------------------

namespace app\system\service;

use app\common\service\BaseService;
use think\App;
use think\facade\Filesystem;

class FileService extends BaseService
{
    /**
     * 本地服务器
     */
    const LOCATION_LOCAL = 4;

    /**
     * 初始化
     * @param App $app
     */
    public function __construct(App $app)
    {
        parent::__construct($app, '文件管理', 'file');
    }

    /**
     * 上传到本地服务器
     * @author 贾二小
     * @since 2021/12/19
     */
    public function upload($file, $location = 4)
    {
        $data = [];
        $msg = '';
        $data['origin_name'] = $file->getOriginalName();
        $data['suffix'] = $file->getOriginalExtension();
        $data['origin_mime'] = $file->getOriginalMime();
        $data['size'] = $file->getSize();
        //上传到本地服务器
        $bool = $this->local($file, $data, $msg);
        if (!empty($msg)) {
            return $msg;
        }
        return $data;
    }

    /**
     * 上传到本地服务器
     * @author 贾二小
     * @since 2021/12/19
     */
    private function local($file, &$data, &$msg): bool
    {
        try {
            // 上传到本地服务器 local
            $pathName = Filesystem::disk('public')->putFile('system' . date('/Y/m/d'), $file, 'md5');
            $config = Filesystem::getConfig();
            $data['location'] = self::LOCATION_LOCAL;
            $data['bucket'] = 'system';
            $data['path'] = $config['disks']['public']['url'] . '/' . $pathName;
            //访问路径
            $data['src'] = $this->request->domain() . $data['path'];
            $this->insertGetId($data);
            return true;
        } catch (\Exception $e) {
            $msg = $e->getMessage();
            return false;
        }
    }
}
